#!/usr/bin/env python
# _*_coding:utf-8_*_

"""
@Time :    2019/9/13 21:55
@Author:  ThinHeader
@File: money_cast.py
@Software: PyCharm
"""
from rest_framework import serializers


def transforms_int(string_a, default=None):
    """把string转换为int"""
    if string_a is None:
        return default

    try:
        return int(str(string_a).strip())
    except ValueError:
        return default


def transforms_float(string_a, default=None):
    """把string转换为float"""
    if string_a is None:
        return default

    try:
        return float(str(string_a).strip())
    except ValueError:
        return default


def float_to_int(float_num, default=None):
    """float to int"""
    if float_num is None:
        return default
    else:
        try:
            return int(float_num)
        except ValueError:
            return default


class FloatToIntField(serializers.Field):

    def to_internal_value(self, data):
        value = float_to_int(round(transforms_float(data, 0) * 100, 2))
        return value

    def to_representation(self, value):
        return int(value)
